import { createRouter, createWebHashHistory } from 'vue-router'
import appConfig from '@/config'
import { getLocalUserInfo } from '@/utils'
import { miscApi } from "@/services"

const PortalPage = () => import('@views/portal/index.vue')
const HomePage = () => import('@views/home/index.vue')
const NoAuthPage = () => import('@views/error-page/401/index.vue')
const NotFoundPage = () => import('@views/error-page/404/index.vue')


import selectedContentRoute from './routes/selected-content'
import myCourseRoute from './routes/my-course'
import myTaskRoute from './routes/my-task'
import myMaterialRoute from './routes/my-material'
import courseRoute from './routes/course'
import messageRoute from './routes/message'
import userInfoRoute from './routes/user-info'
import playerRoute from './routes/player'
import liveRoute from './routes/live'
import docpkgRoute from './routes/doc-pkg'


const router = createRouter({
  history: createWebHashHistory(appConfig.baseUrl),
  routes: [
    {
      path: '/',
      redirect: '/home',
      meta:{
        title:'首页',
        needAuth: false,
      }
    },
    {
      path: '/home',
      name:'首页',
      component: HomePage,
      meta:{
        title:'首页',
        needAuth: false,
      }
    },
    {
      path: '/portal',
      name:'门户',
      component: PortalPage,
      meta:{
        title:'门户',
        needAuth: false,
      }
    },
    selectedContentRoute,
    myCourseRoute,
    myTaskRoute,
    myMaterialRoute,
    courseRoute,
    messageRoute,
    userInfoRoute,
    playerRoute,
    liveRoute,
    docpkgRoute,
    {
      path: '/401',
      component: () => NoAuthPage,
      meta:{
        title:'无权访问',
        needAuth: false,
      }
    },
    {
      path: '/404',
      component: NotFoundPage,
      meta:{
        title:'页面不存在',
        needAuth: false,
      }
    }
  ],
});

// 设置路由前置钩子
router.beforeEach(async (to, from, next) => {
  // console.log('form:', from, ' => to:', to);

  // 若路由地址需要登录权限
  if (to.meta.needAuth === true) {
    const userInfo = getLocalUserInfo();
    // 若用户信息不存在，则跳转到登录页面
    if (!(userInfo && userInfo.username)) {
      let url = appConfig.scnetLogin;
      try {
        const res = await miscApi.getScnetRedirectUrl()
        if (res && res.url) {
          url = res.url;
        }
      } catch(err) {
        
      }
      window.location.href = url;
      return false;
    }
  }

  // 设置页面标题
  document.title = `仿真应用社区${(to.meta && to.meta.title) ? ' | ' + to.meta.title : ''}`;

  next();
});

// 设置路由后置钩子
router.afterEach(() => {
  // console.log('afterEach hook...');
});

export default router;
